package com.rainman.simpleredis.bootstart.configuration;

import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;

import java.time.Duration;


/**
 * 增强@Cacheable的用法
 * 加上自动过期能力
 *
 */
public class SimpleRedisCacheManager extends RedisCacheManager {

    private SimpleRedisProperties simpleRedisProperties;

    public SimpleRedisCacheManager(SimpleRedisProperties simpleRedisProperties,
                                   RedisCacheWriter cacheWriter
            , RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
        this.simpleRedisProperties=simpleRedisProperties;
    }

    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {



        RedisCacheConfiguration redisCacheConfiguration =cacheConfig;

        if(name!=null&&name.contains(simpleRedisProperties.getCacheTimeSpit())){
            String[] split = name.split(simpleRedisProperties.getCacheTimeSpit());

            Long dur=Long.parseLong(split[1]);

            if("MS".equals(simpleRedisProperties.getCacheTimeUnit())
                ||"ms".equals(simpleRedisProperties.getCacheTimeUnit())
            ){

                redisCacheConfiguration=  cacheConfig.entryTtl(Duration.ofMillis(dur));
            }else {

                redisCacheConfiguration=  cacheConfig.entryTtl(Duration.ofSeconds(dur));
            }

        }


        return super.createRedisCache(name,redisCacheConfiguration );
    }


}
